package testview.zhen.com.myapplication.mvvm

import android.content.Intent
import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import com.ldr.base_library.mvvm.BaseActivity
import kotlinx.coroutines.*
import testview.zhen.com.myapplication.databinding.ActivityMainMvvm2Binding


class Main2Activity : BaseActivity<ActivityMainMvvm2Binding, NameViewModel>() {

    val job = Job()
    val ioScope = CoroutineScope(Dispatchers.IO + job)
    var licycleObserver = MyObserver()

    val nameViewModel: NameViewModel by viewModels()

    companion object {
        val TAG = "memory"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initLicycleObserver()
        initViewModel()

        binding.btn2.setOnClickListener {
            val intent = Intent(this, WorkerActivity::class.java)
            startActivity(intent)
        }
    }

    private fun initLicycleObserver() {
        lifecycle.addObserver(licycleObserver)
    }

    private fun initViewModel() {

        //获取viewmodel

        //创建监听 更新UI
        val nameObserver = Observer<String> { newName ->
            binding.nameText.text = newName
        }
        val memoryObserver = Observer<String> { totalMemory ->
            binding.totalMemory.text = totalMemory
        }
        val remainMemoryObserver = Observer<String> { remainMemory ->
            binding.remainMemory.text = remainMemory
        }

        mViewModel.currencyName.observe(this, nameObserver)
        mViewModel.totalMemory.observe(this, memoryObserver)
        mViewModel.remainMemory.observe(this, remainMemoryObserver)
    }

    override val mViewModel: NameViewModel by viewModels()


}
